package com.fg.cloud.factory.controller.agency;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.fg.cloud.common.PageUtils;
import com.fg.cloud.common.StatusCode;
import com.fg.cloud.common.construction.ResultMap;
import com.fg.cloud.common.quantity.ResultType;
import com.fg.cloud.common.reflection.ParamsReflect;
import com.fg.cloud.common.validate.LongUtils;
import com.fg.cloud.framework.controller.BaseController;
import com.fg.cloud.manager.entry.agency.AgencyAddressEntity;
import com.fg.cloud.manager.entry.agency.vo.AgencyAddressVo;
import com.fg.cloud.manager.service.agency.AgencyAddressService;

/**
 * 经销商-地址controller
 * @author around
 * @date 2017-6-22
 */
@Controller
@RequestMapping("/agencyAddress")
public class AgencyAddressController extends BaseController {

	@Autowired
	private AgencyAddressService agencyAddressService;
	
	/**
	 * 详情页信息封装查询
	 * @param request
	 * @param session
	 * @param address
	 * @return String 
	 */
	@RequestMapping(value = "/detail", method = {RequestMethod.POST, RequestMethod.GET})
	@ResponseBody
	public void openPage(HttpServletRequest request, HttpServletResponse response, 
			AgencyAddressEntity address) {
		AgencyAddressEntity entity = agencyAddressService.find(address.getId());
		if(entity == null)
			doResult(response, false, StatusCode.FINDERROR, null, ResultType.FIND_NULL);
		else
			doResult(response, true, StatusCode.FINDSUCCESS, entity, ResultType.FIND_SUCCESS);
	}
	
	/**
	 * 分页查询 前端必传 ageId，确认经销商对应的地址
	 * @param request
	 * @param session
	 * @param page
	 * @param rows
	 * @param sort
	 * @param order
	 * @param agency
	 */
	@RequestMapping(value = "/findList", method = {RequestMethod.POST, RequestMethod.GET})
	@ResponseBody
	public void findList(HttpServletRequest request, HttpServletResponse response, 
			Integer page, Integer rows, String sort, String order,
			AgencyAddressEntity agency) {
		try {
			PageUtils<AgencyAddressEntity> pageinfo = 
					new PageUtils<AgencyAddressEntity>(page, rows, sort, order); 
			Map<String, Object> condition = ParamsReflect.getParamsByReflect(agency);
			pageinfo.setCondition(condition);
			
			agencyAddressService.findList(pageinfo);
			doResult(response,true,StatusCode.FINDSUCCESS, pageinfo, ResultType.FIND_SUCCESS);
		} catch (Exception e) {
			doResult(response,false,StatusCode.FINDERROR, null, e.getMessage());
			e.printStackTrace();
		}
	}
	
	/**
	 * 新增/保存厂商用户信息
	 * @param request
	 * @param response
	 * @param address AgencyAddressEntity
	 */
	@RequestMapping(value = "/saveOrUpdate", method = {RequestMethod.POST})
	@ResponseBody
	public void saveOrUpdate(HttpServletRequest request, HttpServletResponse response, 
			AgencyAddressVo address) {
		if (null == address.getAgeId()) {
			doResult(response, false, StatusCode.LACKVALUE, null, "缺少经销商信息");
			return;
		}
		
		if(StringUtils.isNotEmpty(address.getAdministrative())) {
			if(address.getAdministrative().length() > 0) {
				List<ResultMap> array = JSON.parseArray(address.getAdministrative(), 
						ResultMap.class);
				if (array.size() == 3)
					address.setCity(array.get(1).getLabel());
				else
					address.setCity(array.get(0).getLabel());
				address.setArea(array.get(array.size()-1).getLabel());
				address.setProvince(array.get(0).getLabel());
			}
		}

		try {
			boolean flag = agencyAddressService.verifyUniquely(address);
			if (!flag) {
				doResult(response, false, StatusCode.SAVEERROR, null, "重复的地址信息");
				return;
			}
			
			setUpdateInfo(address, request);
			//id为空新增、不为空保存
			if(null == address.getId()) {
				setCreateInfo(address, request);
				address.setStatus(1);
				flag = agencyAddressService.insertSelective(address);
			} else {
				flag = agencyAddressService.updateByPrimaryKeySelective(address);
			}
			doResult(response, flag, flag ? StatusCode.SAVESUCCESS:StatusCode.SAVEERROR, null, 
					flag ? ResultType.SAVE_SUCCESS : ResultType.SAVE_FAULT);
		} catch (Exception e) {
			doResult(response, false, StatusCode.SAVEERROR, null, e.getMessage());
			e.printStackTrace();
		}
	}
	
	/**
	 * 删除信息
	 * @param request
	 * @param response
	 * @param ids String => x,x,x
	 * @throws IOException 
	 */
	@RequestMapping(value = "/deletes", method = {RequestMethod.POST, RequestMethod.GET})
	@ResponseBody
	public void deletes(HttpServletRequest request, HttpServletResponse response, 
			String ids, Long ageId) throws IOException {
		try {
			if(StringUtils.isEmpty(ids) || ids.split(",").length == 0) {
				doResult(response, false, StatusCode.REMOVEERROR, null, ResultType.INPUT_ERROR);
				return;
			}
			boolean flag = false;
			flag = agencyAddressService.deletes(getCurrentFactoryUser().getId(),
					ageId, LongUtils.convert(ids.split("[, ]+")));
			
			doResult(response, flag, flag ? StatusCode.REMOVESUCCESS:StatusCode.REMOVEERROR, 
					null, flag ? ResultType.REMOVE_SUCCESS : ResultType.REMOVE_FAULT);
		} catch (Exception e) {
			doResult(response, false, StatusCode.REMOVEERROR, null, e.getMessage());
			e.printStackTrace();
		}
	}
	
	
	@RequestMapping(value = "/findBySelect", method = {RequestMethod.POST, RequestMethod.GET})
	@ResponseBody
	public void findBySelect(HttpServletRequest request, HttpServletResponse response, 
			Long ageId) {
		try {
			if (null == ageId) {
				doResult(response,false,StatusCode.LACKVALUE, null, "经销商ID为空");
				return;
			}
			doResult(response, true, StatusCode.FINDSUCCESS, 
					agencyAddressService.selectAll(ageId), ResultType.FIND_SUCCESS);
		} catch (Exception e) {
			doResult(response,false,StatusCode.FINDERROR, null, e.getMessage());
			e.printStackTrace();
		}
	}
	
	
}
